﻿using UnityEngine;
using System.Collections;

public class Beer : Object, ICanSwim {

	public Mob mob;
	public Bar bar;
	public int barloc;
	public int barvel;
	public bool isEmpty = false;

	public void create() {
		mob = new Mob ();
		mob.create ("Beer");
	}

	public void init(Bar a, int _barloc = 0, bool empty = false) {
		bar = a;
		isEmpty = empty;

		mob.init(Tappa.game.data.beer);
		mob.pos = a.data.beerStart.pos;
		barloc = _barloc;
		barvel = Tappa.game.data.constants.beerSpeedFull;

		if (isEmpty) {
			mob.dataSprite = Tappa.game.data.beerEmpty;
			barvel = -Tappa.game.data.constants.beerSpeedEmpty;
		}

		mob.upd ();

		falling = false;
		falltimer = 0;

	}

	bool falling = false;
	int falltime = 3000;
	int falltimer = 0;
	public void upd() {

		barloc = barloc + barvel;
		int len = bar.data.barLengthScale;
		if (isEmpty) {
			if (Tappa.game.bars [Tappa.game.itsame.bar] == bar) {
				if (barloc <= Tappa.game.itsame.runpos) {
					Score.add (Score.Value.Catch);
					isAlive = false;
				}
			}
		}
		if (isAlive && (barloc > len || barloc < 0)) {
			isAlive = false;
			Tappa.game.x_x();
			return;
			Mob.temporalSingularity = this;
			barvel = 0;
			//barloc = 0;
			falling = true;
			falltimer = 0;		
		}
		if (falling) {
			falltimer++;
			if (falltimer > falltime) {
				Mob.temporalSingularity = null;
				isAlive = false;
			}
		}
		if (barloc > len) {
			barloc = 2*len - barloc;
			barvel = -barvel;
			barvel = (int)Mathf.Sign (barvel) * 8;
		}

		xy pos;
		xy pos1 = bar.data.beerStart.pos;
		xy pos2 = bar.data.beerEnd.pos;
		float tween = (float)barloc / len;
		pos.x = (int)Mathf.Lerp (pos1.x, pos2.x, tween);
		pos.y = (int)Mathf.Lerp (pos1.y, pos2.y, tween) - (100*falltimer / falltime);

		mob.pos = pos;
		mob.r.sortingOrder = barloc;
		mob.upd();

	}

	public bool isAlive = false;
	public bool wantsToGoBackInThePool() {
		return !isAlive;
	}
	public void getInThePool() {
		isAlive = false;
		mob.go.SetActive (false);
	}
	public void getOutOfThePool() {
		isAlive = true;
		mob.go.SetActive (true);
	}

}
